package org.mtdownload.dialogs;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.net.URL;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;

import org.mtdownload.download.DownloadTask;
import org.mtdownload.utils.PreferencesManager;

public class DownloadInfoPanel extends JPanel {

	private static final long serialVersionUID = 3545803169478226225L;

	private JTextField url=new JTextField();
	private JTextField referer=new JTextField();
	private JTextField saveTo=new JTextField();
	private JSpinner splitFile=new JSpinner(new SpinnerNumberModel(PreferencesManager.getDefaultThreadsNumber(),1,100,1));
	private JTextField username=new JTextField();
	private JPasswordField password=new JPasswordField();	
	private JCheckBox loginCheck=new JCheckBox("Login to server");
	private JComboBox controlStartCombo=new JComboBox();
	
	private static final String CONTROL_START_NOW="Now!!!";
	private static final String CONTROL_START_LATER="Later";
	private boolean loadUrlsFromFile=false;
	
	public DownloadInfoPanel(boolean loadUrlsFromFile) {
		super();
		this.loadUrlsFromFile=loadUrlsFromFile;
		init();
	}
	
	private void init(){
		setLayout(new GridBagLayout());
		JLabel urlLabel=new JLabel((loadUrlsFromFile?"File/Url:":"Url:"));
		urlLabel.setDisplayedMnemonic(loadUrlsFromFile?KeyEvent.VK_F:KeyEvent.VK_U);
		urlLabel.setLabelFor(url);		
		JLabel refererLabel=new JLabel("Referer:");
		refererLabel.setDisplayedMnemonic(KeyEvent.VK_R);
		refererLabel.setLabelFor(referer);
		JLabel saveToLabel=new JLabel("Save to:");
		saveToLabel.setDisplayedMnemonic(KeyEvent.VK_S);
		saveToLabel.setLabelFor(saveTo);
		JButton browseFileButton=new JButton("Browse");
		browseFileButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				browseFile();
			}			
		});
		if(loadUrlsFromFile){
			url.setToolTipText("Type here the full URL (e.g. http://www.mydomain.com/) or the path to a text file or HTML resource. The file will be parsed for URL's.");
		}else{
			url.setToolTipText("The URL has to be in fully specified (e.g. http://www.mysite.com/file.iso)");
		}
		JButton browseDirButton=new JButton("Browse");
		browseDirButton.setMnemonic(KeyEvent.VK_B);
		browseDirButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				browseDirectory();
			}			
		});
		JLabel splitFileLabel1=new JLabel("Split file in ");
			splitFileLabel1.setDisplayedMnemonic(KeyEvent.VK_P);
			splitFileLabel1.setLabelFor(splitFile);
		JLabel splitFileLabel2=new JLabel(" parts simultaneous");
		JLabel controlStartLabel=new JLabel("Start:");
		controlStartLabel.setDisplayedMnemonic(KeyEvent.VK_T);
		controlStartLabel.setLabelFor(controlStartCombo);
		controlStartCombo.setPrototypeDisplayValue("XXXXXXX");
		controlStartCombo.addItem(CONTROL_START_NOW);
		controlStartCombo.addItem(CONTROL_START_LATER);
		controlStartCombo.setSelectedIndex(0);
		controlStartCombo.setPreferredSize(new Dimension(100,controlStartCombo.getPreferredSize().height));
		JPanel loginPanel=createLoginPanel();		
		
		add(urlLabel,new GridBagConstraints(0,0,1,1,0,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(10,10,0,0),0,0));
		add(url,new GridBagConstraints(1,0,loadUrlsFromFile?1:2,1,1,0,GridBagConstraints.WEST,GridBagConstraints.HORIZONTAL,new Insets(10,5,0,0),0,0));
		if(loadUrlsFromFile){
			add(browseFileButton,new GridBagConstraints(2,0,1,1,0,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,0,0,0),0,0));	
		}
		add(refererLabel,new GridBagConstraints(0,1,1,1,0,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,10,0,0),0,0));
		add(referer,new GridBagConstraints(1,1,2,1,1,0,GridBagConstraints.WEST,GridBagConstraints.HORIZONTAL,new Insets(5,5,0,0),0,0));		
		add(saveToLabel,new GridBagConstraints(0,2,1,1,0,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,10,0,0),0,0));
		add(saveTo,new GridBagConstraints(1,2,1,1,1,0,GridBagConstraints.WEST,GridBagConstraints.HORIZONTAL,new Insets(5,5,0,0),0,0));		
		add(browseDirButton,new GridBagConstraints(2,2,1,1,0,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,0,0,0),0,0));
		add(splitFileLabel1,new GridBagConstraints(0,3,1,1,0,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,10,0,0),0,0));
		JPanel splitFilePanel=new JPanel(new FlowLayout(FlowLayout.LEADING,0,5));
		add(splitFilePanel,new GridBagConstraints(1,3,2,1,1,0,GridBagConstraints.WEST,GridBagConstraints.HORIZONTAL,new Insets(5,5,0,0),0,0));
		splitFilePanel.add(splitFile);
		splitFilePanel.add(splitFileLabel2);
		add(controlStartLabel,new GridBagConstraints(0,4,1,1,0,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,10,0,0),0,0));
		add(controlStartCombo,new GridBagConstraints(1,4,2,1,1,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,5,0,0),0,0));
		
		add(loginPanel,new GridBagConstraints(0,5,2,1,1,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,5,0,0),0,0));		
		add(new JPanel(),new GridBagConstraints(0,6,3,1,1,1,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,0),0,0));
		
		String defaultUrlValue=null;
		try{
			Object obj=Toolkit.getDefaultToolkit().getSystemClipboard().getData(new DataFlavor(String.class,"text/text"));
			if(obj!=null && obj instanceof String){
				defaultUrlValue=(String)obj;
			}
		}catch(Exception exc){/*ignored*/}
		if(defaultUrlValue!=null){
			url.setText(defaultUrlValue);
		}
		saveTo.setText(PreferencesManager.getDefaultSaveDir());
	}

	
	protected void browseFile() {
		JFileChooser chooser=new JFileChooser(url.getText());
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int result=chooser.showOpenDialog(this);
		if(result==JFileChooser.APPROVE_OPTION){
			url.setText(chooser.getSelectedFile().getAbsolutePath());
		}		
	}

	private JPanel createLoginPanel(){
		JPanel loginPanel=new JPanel(new GridBagLayout());		
		loginPanel.setBorder(BorderFactory.createTitledBorder("Login"));
		loginPanel.setPreferredSize(new Dimension(200,100));
		JLabel usernameLabel=new JLabel("Username:");
		usernameLabel.setDisplayedMnemonic(KeyEvent.VK_N);
		usernameLabel.setLabelFor(username);
		JLabel passwordLabel=new JLabel("Password:");
		passwordLabel.setDisplayedMnemonic(KeyEvent.VK_A);
		passwordLabel.setLabelFor(password);
		//username.setPreferredSize(new Dimension(150,20));
		password.setPreferredSize(username.getPreferredSize());
		username.setEnabled(false);
		password.setEnabled(false);
		loginCheck.setSelected(false);
		loginCheck.addItemListener(new ItemListener(){
			public void itemStateChanged(ItemEvent e) {
				username.setEnabled(e.getStateChange()==ItemEvent.SELECTED);
				password.setEnabled(e.getStateChange()==ItemEvent.SELECTED);
				if(e.getStateChange()==ItemEvent.SELECTED){
					username.requestFocus();
				}
			}			
		});
		
		loginPanel.add(loginCheck,new GridBagConstraints(0,0,2,1,1,0,GridBagConstraints.WEST,GridBagConstraints.HORIZONTAL,new Insets(10,10,0,0),0,0));
		loginPanel.add(usernameLabel,new GridBagConstraints(0,1,1,1,0,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(0,10,0,0),0,0));
		loginPanel.add(username,new GridBagConstraints(1,1,1,1,1,0,GridBagConstraints.WEST,GridBagConstraints.HORIZONTAL,new Insets(0,5,0,0),0,0));
		loginPanel.add(passwordLabel,new GridBagConstraints(0,2,1,1,0,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,10,0,0),0,0));
		loginPanel.add(password,new GridBagConstraints(1,2,1,1,1,0,GridBagConstraints.WEST,GridBagConstraints.HORIZONTAL,new Insets(5,5,0,0),0,0));
		loginPanel.add(new JPanel(),new GridBagConstraints(0,3,2,1,1,1,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,0),0,0));
		
		return loginPanel;
	}

	private void browseDirectory(){
		JFileChooser chooser=new JFileChooser(saveTo.getText());
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int result=chooser.showOpenDialog(this);
		if(result==JFileChooser.APPROVE_OPTION){
			saveTo.setText(chooser.getSelectedFile().getAbsolutePath());
		}
	}
	
/**	
	private JComboBox controlStartCombo=new JComboBox();
 */
	public String getURL(){
		if(url.getText().toLowerCase().startsWith("www")){
			//the user ommited http://
			url.setText("http://"+url.getText());
		}
		if(url.getText().toLowerCase().startsWith("ftp")&&!url.getText().toLowerCase().startsWith("ftp://")){
			//the user ommited ftp://
			url.setText("ftp://"+url.getText());			
		}
		return url.getText();
	}	
	public String getReferer(){
		return referer.getText();
	}
	public String getDestinationFile(){
		if(getSaveToDir()!=null && getSaveToDir().length()>0){
			String fileName="default_download.file";
			try {
				URL _url=new URL(getURL());
				String path=_url.getPath();
				int index=path.lastIndexOf('/');
				if(index>=0){
					fileName=path.substring(index+1);
				}				
			} catch (Exception e) {
				//ignored				
			}
			return getSaveToDir()+java.io.File.separator+fileName;
		}
		return "";
	}
	public String getSaveToDir(){
		return saveTo.getText();
	}
	public int getSplitFileNumber(){
		return ((Integer)splitFile.getValue()).intValue();
	}
	public String getUsername(){
		return username.getText();
	}
	public String getPassword(){
		return String.valueOf(password.getPassword());
	}
	public boolean isLogin(){
		return loginCheck.isSelected();
	}
	public int getStartTime(){
		Object obj=controlStartCombo.getSelectedItem();
		if(CONTROL_START_NOW.equals(obj)){
			return DownloadTask.START_NOW;
		}		
		return DownloadTask.START_MANUALLY;		
	}
}
